<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>深拷贝和浅拷贝</title>
</head>

<body>
    <p>拷贝原理</p>
    <pre>
        浅拷贝：只拷贝对象的属性值

        深拷贝：拷贝对象的属性值和内存地址（递归）
    </pre>
</body>
<script>
    /* let person = Object.create({ id: 'personId' }, {
        info_hobby: {
            value: 'baseball',
            enumerable: true
        },
        prevbookread: {
            value: '红楼梦',
            enumerable: true
        },
        nowbookread: {
            value: '西游记'
        }
    })
    console.log('person：', person);
    let bob = Object.assign({}, person)
    console.log('bob：', bob); */

    let obj = {
        name: 'Tom',
        age: '12',
        hobby: ['baseball', 'cartoon']
    }

    let copyobj = shallowCopy(obj)
    let copyobj2 = deepCopy(obj)
    obj.name = 'Jerry'
    console.log('原对象:', obj);
    console.log('浅拷贝:', copyobj);
    console.log('深拷贝:', copyobj2);

    // 浅拷贝
    function shallowCopy(obj) {
       /*  let newObj = Array.isArray(obj) ? [] : {}
        for (let i in obj) {
            newObj[i] = obj[i]
        }
        return newObj */

        let newObj = {...obj}
        return newObj
    }
    // 深拷贝
    function deepCopy(obj) {
        let newObj = Array.isArray(obj) ? [] : {}
        if (obj && typeof obj === 'object') {
            for (let key in obj) {
                if (obj.hasOwnProperty(key)) {
                    if (obj[key] && typeof obj[key] === 'object') {
                        newObj[key] = deepCopy(obj[key])
                    } else {
                        newObj[key] = obj[key]
                    }
                }
            }
        }

        return newObj
    }
</script>

</html>